﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace InstallManager.Msi
{
    internal class MsiConnection : IDisposable
    {
        private IntPtr _database;

        private bool _disposed;

        private string _fileName;

        internal IntPtr Handle
        {
            get
            {
                this.CheckDisposed();
                return this._database;
            }
        }

        public MsiConnection(string fileName)
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException(string.Concat(fileName, " not found."));
            }
            this._fileName = fileName;
        }

        private void CheckDisposed()
        {
            if (this._disposed)
            {
                throw new ObjectDisposedException("MSI");
            }
        }

        public void Close()
        {
            this.CheckDisposed();
            if (this._database != IntPtr.Zero)
            {
                MsiDbInterop.MsiCloseHandle(this._database);
                this._database = IntPtr.Zero;
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!this._disposed && this._database != IntPtr.Zero)
            {
                MsiDbInterop.MsiCloseHandle(this._database);
                this._database = IntPtr.Zero;
                this._disposed = true;
            }
        }

       

        public void Open()
        {
            this.CheckDisposed();
            if (this._database != IntPtr.Zero)
            {
                throw new InvalidOperationException("Database already opened.");
            }
            uint num = MsiDbInterop.MsiOpenDatabase(this._fileName, 0, out this._database);
            if (num != 0)
            {
                throw new Exception(string.Concat("Failed to open database. Error code = ", num));
            }
        }
    }
}
